package com.hjq.fcloud.app

import android.content.Intent
import android.media.ThumbnailUtils
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.View
import androidx.annotation.StringRes
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.hjq.bar.TitleBar
import com.hjq.base.BaseActivity
import com.hjq.base.BaseDialog
import com.hjq.fcloud.R
import com.hjq.fcloud.action.TitleBarAction
import com.hjq.fcloud.action.ToastAction
import com.hjq.fcloud.bean.CommonFileBean
import com.hjq.fcloud.http.model.HttpData
import com.hjq.fcloud.ui.dialog.WaitDialog
import com.hjq.fcloud.utils.FileUtils
import com.hjq.fcloud.widget.loadandretry.LoadingAndRetryManager
import com.hjq.fcloud.widget.loadandretry.OnLoadingAndRetryListener
import com.hjq.http.listener.OnHttpListener
import com.hjq.toast.ToastUtils
import okhttp3.Call
import org.greenrobot.eventbus.EventBus

/**
 *    author : Android 轮子哥
 *    github : https://github.com/getActivity/AndroidProject-Kotlin
 *    time   : 2018/10/18
 *    desc   : Activity 业务基类
 */
abstract class AppActivity : BaseActivity(),
    ToastAction, TitleBarAction, OnHttpListener<Any> {

    /** 标题栏对象 */
    private var titleBar: TitleBar? = null

    /** 状态栏沉浸 */
    private var immersionBar: ImmersionBar? = null

    /** 加载对话框 */
    private var dialog: BaseDialog? = null
    private var mProgressDialog: BaseDialog? = null

    /** 对话框数量 */
    private var dialogCount: Int = 0

    var mLoadingAndRetryManager: LoadingAndRetryManager? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (userEventBus()) {
            EventBus.getDefault().register(this)
        }
    }

    //是否启用eventbus，默认false不启用
    open fun userEventBus(): Boolean {
        return false
    }

    /**
     * 当前加载对话框是否在显示中
     */
    open fun isShowDialog(): Boolean {
        return dialog != null && dialog!!.isShowing
    }

    /**
     * 显示加载对话框
     */
    open fun showDialog() {
        if (isFinishing || isDestroyed) {
            return
        }
        dialogCount++
        postDelayed(Runnable {
            if ((dialogCount <= 0) || isFinishing || isDestroyed) {
                return@Runnable
            }
            if (dialog == null) {
                dialog = WaitDialog.Builder(this)
                    .setCancelable(false)
                    .create()
            }
            if (!dialog!!.isShowing) {
                dialog!!.show()
            }
        }, 0)
//        }, 300)
    }

    /**
     * 隐藏加载对话框
     */
    open fun hideDialog() {
        if (isFinishing || isDestroyed) {
            return
        }
        if (dialogCount > 0) {
            dialogCount--
        }
        if ((dialogCount != 0) || (dialog == null) || !dialog!!.isShowing) {
            return
        }
        dialog?.dismiss()
    }


    var mProgressDialogBuilder: WaitDialog.Builder? = null
    open fun showProgressDialog(contentMsg: String?) {
        if (isFinishing || isDestroyed) {
            return
        }
        if (mProgressDialog == null) {
            mProgressDialogBuilder = WaitDialog.Builder(this)
            mProgressDialogBuilder!!.setCancelable(false)
            mProgressDialog = mProgressDialogBuilder!!.create()
        }
        if (!mProgressDialog!!.isShowing()) {
            mProgressDialog!!.show()
        }
        mProgressDialogBuilder!!.setMessage(contentMsg)
    }

    open fun hideProgressDialog() {
        if (isFinishing || isDestroyed) {
            return
        }
        if (mProgressDialog?.isShowing() == true) {
            mProgressDialog?.dismiss()
        }
    }

    override fun initLayout() {
        super.initLayout()

        val titleBar = getTitleBar()
        titleBar?.setOnTitleBarListener(this)

        // 初始化沉浸式状态栏
        if (isStatusBarEnabled()) {
            getStatusBarConfig().init()

            // 设置标题栏沉浸
            if (titleBar != null) {
                ImmersionBar.setTitleBar(this, titleBar)
            }
        }
    }

    /**
     * 是否使用沉浸式状态栏
     */
    protected open fun isStatusBarEnabled(): Boolean {
        return true
    }

    /**
     * 状态栏字体深色模式
     */
    open fun isStatusBarDarkFont(): Boolean {
        return false
    }

    /**
     * 获取状态栏沉浸的配置对象
     */
    open fun getStatusBarConfig(): ImmersionBar {
        if (immersionBar == null) {
            immersionBar = createStatusBarConfig()
        }
        return immersionBar!!
    }

    /**
     * 初始化沉浸式状态栏
     */
    protected open fun createStatusBarConfig(): ImmersionBar {
        return ImmersionBar.with(this) // 默认状态栏字体颜色为黑色
            .statusBarDarkFont(isStatusBarDarkFont()) // 指定导航栏背景颜色
            .navigationBarColor(R.color.white) // 状态栏字体和导航栏内容自动变色，必须指定状态栏颜色和导航栏颜色才可以自动变色
            .autoDarkModeEnable(true, 0.2f)
            .keyboardEnable(true) //解决软键盘与底部输入框冲突问题，默认为false，还有一个重载方法，可以指定软键盘mode
    }

    /**
     * 设置标题栏的标题
     */
    override fun setTitle(@StringRes id: Int) {
        title = getString(id)
    }

    /**
     * 设置标题栏的标题
     */
    override fun setTitle(title: CharSequence?) {
        super<BaseActivity>.setTitle(title)
        getTitleBar()?.title = title
    }

    override fun getTitleBar(): TitleBar? {
        if (titleBar == null) {
            titleBar = obtainTitleBar(getContentView())
        }
        return titleBar
    }

    override fun onLeftClick(view: View) {
        onBackPressed()
    }

    override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
        super.startActivityForResult(intent, requestCode, options)
        overridePendingTransition(R.anim.right_in_activity, R.anim.right_out_activity)
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.left_in_activity, R.anim.left_out_activity)
    }

    /**
     * [OnHttpListener]
     */
    override fun onStart(call: Call) {
        showDialog()
    }

    override fun onSucceed(result: Any) {
        if (result is HttpData<*>) {
            toast(result.getMessage())
        }
    }

    override fun onFail(e: Exception) {
        toast(e.message)
    }

    override fun onEnd(call: Call) {
        hideDialog()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (userEventBus()) {
            EventBus.getDefault().unregister(this)
        }
        if (isShowDialog()) {
            hideDialog()
        }
        dialog = null
    }


    fun showToast(obj: Any?) {
        ToastUtils.show(obj)
    }

    /**
     * 通过url得到请求服务器需要的对象
     */
    fun getRequestFileList(urlList: List<CommonFileBean>): ArrayList<HashMap<String, String>> {
        var ret = ArrayList<HashMap<String, String>>()
        urlList.forEach {
            var url = it.url
            var itemMap = HashMap<String, String>()
            itemMap.put("name", FileUtils.getFileName(url))
            itemMap.put("url", url)
            if (!TextUtils.isEmpty(it.videoThumbnailUrl)) {
                itemMap.put("url2", it.videoThumbnailUrl)
            }
            ret.add(itemMap)
        }
        return ret
    }


    //==========  状态view start ==============

    override fun setContentView(layoutResID: Int) {
        super.setContentView(layoutResID)
        initStateLayout()
    }

    /**
     * 初始化StateLayout
     */
    private fun initStateLayout() {
        if (getStateLayout() != null) {
            mLoadingAndRetryManager =
                LoadingAndRetryManager(getStateLayout(), object : OnLoadingAndRetryListener() {
                    override fun setRetryEvent(retryView: View) {
                        retryView.findViewById<View>(R.id.linear_retry)
                            .setOnClickListener { clickRetry() }
                    }
                })
        }
    }

    open fun clickRetry() {}


    open fun getStateLayout(): View? {
        return null
    }

    open fun showAppEmpty() {
        mLoadingAndRetryManager?.showAppEmpty()
    }

    open fun showAppEmpty(emptyMsg: String?) {
        mLoadingAndRetryManager?.showAppEmpty(emptyMsg)
    }

    open fun showAppLoading() {
        mLoadingAndRetryManager?.showAppLoading()
    }

    open fun showAppContent() {
        mLoadingAndRetryManager?.showAppContent()
    }

    open fun showAppRetry(warning: String?) {
        if (!TextUtils.isEmpty(warning)) {
            mLoadingAndRetryManager?.showAppRetry()
            mLoadingAndRetryManager?.setWarningText(warning)
        } else {
            showAppRetry()
        }
    }

    open fun showAppRetry() {
        val warning = "加载失败，点击屏幕重新加载"
        mLoadingAndRetryManager?.showAppRetry()
        mLoadingAndRetryManager?.setWarningText(warning)
    }
    //==========  状态view end ==============
}